<?php

namespace app\admin\controller\user;

use app\api\extra\CommonCode;
use app\api\service\UserService;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\UserExtra;
use app\common\model\Users;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where("user.id","<>",1196416)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if(!isset($params['invite_code'])){
            $this->error(__('邀请码必须！', ''));
        }
        if(!isset($params['mobile'])){
            $this->error(__('手机号必须！', ''));
        }

        $parent  = $this->checkInviteCode($params['invite_code']);

        $salt = Random::alnum();
        $data = [
            'group_id' => 1,
            'username' => $params['mobile'],
            'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $params['mobile']) ? substr_replace($params['mobile'], '****', 3, 4) : $params['mobile'],
            'mobile' => $params['mobile'],
            'password' => md5(md5($params['password']) . $salt),
            'salt' => $salt,
            'level' => 0,
            'pid' => UserService::getInstance()->getDirectPush($parent->id),
            'direct_push' => $parent->id,
            'is_sys' => 2,
            'invite_code' => $this->getInviteCode(),
            'status'    => 'normal'
        ];
        $old_user = false;//Users::where('mobile', $data['mobile'])->find();
        $data['star'] = $old_user ? $old_user->star : 0;
        $a = \app\common\model\User::where('mobile',$data['mobile'])->find();
        if ($a) {
            $this->error(__('手机号已存在！', ''));
        }
        //  更新直推人数
        \app\admin\model\User::where('id',$parent->id)->setInc('direct_num', 1);

        UserService::getInstance()->getUpdateAllNum($data['pid']);
        $result = false;
        Db::startTrans();
        try {
            $user = \app\common\model\User::create($data, true);
            $extra_data = [
                'user_id' => $user->id,
                'invite_code' => $data['invite_code'],
                'pid' => $data['pid'],
                'star' => $data['star'],
                'score' => 0
            ];
            $result = UserExtra::create($extra_data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    public function getInviteCode()
    {
        $prefix = config('oem.InviteCodePrefix');
        do {
            $temp_code = $prefix . rand(10000, 99999);
        } while (UserExtra::where(['invite_code' => $temp_code])->find());

        return $temp_code;
    }

    /**
     * 验证邀请码是否存在
     * @param $code
     * @throws \think\exception\DbException
     */
    public function checkInviteCode($code){
        $parentAgentInfo = \app\admin\model\User::where(['invite_code' => $code])->find();
        if (empty($parentAgentInfo)) {
            $this->error(__('邀请码无效', ''));
        }
        return $parentAgentInfo;
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);
        if($params['score'] != $row['score']){
            $params['money'] = $params['score'];
        }

        if($params['star'] != $row['star']){
            $params['lamp'] = 1;
            $params['first_lamp_time'] = time();
        }
        if(isset($params["mobile"])){
            $a = \app\common\model\User::where('mobile',$params['mobile'])->where('id',"<>", $params['id'])->find();
            if ($a) {
                $this->error(__('手机号已存在！', ''));
            }
            if($row["mobile"] == $row["username"]){
                $params["nickname"] = substr($params["mobile"], 0, 3) . "****" . substr($params["mobile"], -4, 4);
                $params["username"] = ($params["mobile"]);
            }
        }
//        return 123456;
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            UserExtra::update(['score' => $params['score'],'star'=>$params['star']], ['user_id' => $row['id']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    
    
    public function down_excel(){
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        $data = [];
        $ids    = input("param.ids");
        $filter = input("param.filter");
        $op     = input("param.op");
        $where1  = [];
        if ($ids != "all"){
            $where1["id"] = ["in",explode(",",$ids)];
        }
        $this->request->get(["filter"=>json_encode($filter),'op'=>json_encode($op)]);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($where1)
            ->order($sort, $order)
            ->select();
        foreach ($list as $row) {
//            return json($row);
            $data[] = [
                $row["id"],
                $row["username"],
                $row["nickname"],
                $row["mobile"],
                empty($row["balance"]) ? 0 : $row["balance"],
                empty($row["score"]) ? 0 : $row["score"],
                // $row["score"],
                date("Y-m-d H:i:s",$row["createtime"]),
                $row["pid"],
                $row["direct_push"],
                $row["star"],
                $row["lamp"] == 0 ? "灭灯" : "亮灯" ,
//                $row["product_orders"],
                $row["promotion_money"],
                $row["all_order"],
//                $row["id"],
//                $row["id"],
            ];
        }

        $excel = new Spreadsheet();
        $excel->getProperties()
            ->setCreator("FastAdmin")
            ->setLastModifiedBy("FastAdmin")
            ->setTitle("订单数据")
            ->setSubject("Subject");
        $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $excel->getDefaultStyle()->getFont()->setSize(12);
        $excel->getDefaultStyle()->applyFromArray(
            array(
                'fill'      => array(
                    'type'  => Fill::FILL_SOLID,
                    'color' => array('rgb' => '000000')
                ),
                'font'      => array(
                    'color' => array('rgb' => "000000"),
                ),
                'alignment' => array(
                    'vertical'   => Alignment::VERTICAL_CENTER,
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'indent'     => 1
                ),
                'borders'   => array(
                    'allborders' => array('style' => Border::BORDER_THIN),
                )
            ));

        $worksheet = $excel->setActiveSheetIndex(0);
        $worksheet->setTitle('订单数据');

        $worksheet->getColumnDimension('B')->setWidth(20);
        $worksheet->getColumnDimension('C')->setWidth(20);
        $worksheet->getColumnDimension('D')->setWidth(20);
        $worksheet->getColumnDimension('G')->setWidth(25);
//        $worksheet->getColumnDimension('H')->setWidth(25);
//        $worksheet->getColumnDimension('J')->setWidth(20);
//        $worksheet->getColumnDimension('K')->setWidth(20);
//        $worksheet->getColumnDimension('L')->setWidth(35);
        $worksheet->getColumnDimension('M')->setWidth(12);

        $worksheet->setCellValue('A1', '用户编号');
        $worksheet->setCellValueExplicit('B1', '用户名',"str");
        $worksheet->setCellValueExplicit('C1', '昵称',"str");
        $worksheet->setCellValueExplicit('D1', '手机号',"str");
        $worksheet->setCellValueExplicit('E1', '余额',"str");
        $worksheet->setCellValue('F1', '积分');
        $worksheet->setCellValue('G1', '加入时间');
        $worksheet->setCellValueExplicit('H1', '上级ID',"str");
        $worksheet->setCellValue('I1', '直推ID');
        $worksheet->setCellValue('J1', '星数');
        $worksheet->setCellValue('K1', '亮灯状态');
        $worksheet->setCellValueExplicit('L1', '晋升业绩',"str");

        $worksheet->setCellValue('M1', '所有爆单金额');

        $worksheet->fromArray($data, NULL, 'A2');

        $excel->createSheet();
        $title = date("YmdHis");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = IOFactory::createWriter($excel, 'Xlsx');
        $objWriter->save('php://output');
    }


    public function money($ids = null){
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!isset($params["soc"])){
            $this->error("缺少必要参数");
        }elseif($params["soc"] < 0){
            $this->error("增加积分必须为正数");
        }elseif($params["soc"] == 0){
            $this->error("增加积分不可为0");
        }
        $result = false;
        Db::startTrans();
        try {
            db("user")->where("id",$ids)->inc("money",$params["soc"])->inc("score",$params["soc"])->update(["updatetime"=>time()]);
            $data = [
                "user_id"=>$ids,
                "money"=>$params["soc"],
                "before"=>$row["money"],
                "after"=>bcadd($params["soc"],$row["money"],2),
                "memo"=>$params["shuo"],
                "type"=>"sys",
                "createtime"=>time(),
            ];
            db("user_money_log")->insert($data);
            unset($data["money"]);
            unset($data["type"]);
            $data["score"] = $params["soc"];
            $data["before"] = $row["score"];
            $data["after"] = bcadd($params["soc"],$row["score"],2);
            $result = db("user_score_log")->insert($data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    
    
    public function bank($ids = null){
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!isset($params["banklist"]) || empty($params["banklist"])){
            $this->error("缺少必要参数 银行名称");
        }
        if(!isset($params["bankcard"]) || empty($params["bankcard"])){
            $this->error("缺少必要参数 卡号");
        }
        if(!isset($params["uname"]) || empty($params["uname"])){
            $this->error("缺少必要参数 持卡人姓名");
        }
        if(!isset($params["mobile"]) || empty($params["mobile"])){
            $this->error("缺少必要参数 持卡人手机");
        }
//          `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
//   `user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
//   `username` varchar(4) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '持卡人姓名',
//   `` varchar(11) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '手机号',
//   `` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '类型',
//   `` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '名称',
//   `` int(1) DEFAULT '0' COMMENT '卡片类型',
//   `` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '账户',
//   `createtime` int(10) DEFAULT NULL COMMENT '创建时间',
        // return json($this->getbankname($params["banklist"]));
        $data = [
            "user_id" => $ids,
            "username" => $params["uname"],
            "mobile" => $params["mobile"],
            "bankCode" => $params["banklist"],
            "bankName" => $this->getbankname($params["banklist"]),
            "cardType" => 0,
            "cardCode" => $params["bankcard"],
            "createtime" => time()
            
        ];
        $result = false;
        Db::startTrans();
        try {
            $result = db("wanlshop_pay_account")->insert($data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    
    public function getbankname($key){
        $list = [
    	   "ALIPAY"=>"支付宝账户","ICBC"=>"工商银行","ABC"=>"农业银行","PSBC"=>"邮储银行","CCB"=>"建设银行",
    	   "CMB"=>"招商银行","BOC"=>"中国银行","COMM"=>"交通银行","SPDB"=>"浦发银行","GDB"=>"广发银行",
    	   "CMBC"=>"民生银行","PAB"=>"平安银行","CEB"=>"光大银行","CIB"=>"兴业银行","CITIC"=>"中信银行"
	    ];
	   // $row = array_flip($list);
        return $list[$key];
    }
    
    
    // public function banklist(){
    //     $list = [];
    //     $list["list"] = [
    //             ["id"=>"1","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"2","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"3","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"4","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"5","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"6","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"8","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"7","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"9","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"10","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"11","name"=>"支付宝账户","pid"=>0],
    //             ["id"=>"12","name"=>"支付宝账户","pid"=>0],
    //         ];
    //      return json($list);
         
    //      [
	   //     "ALIPAY"=>"支付宝账户","ICBC"=>"工商银行","ABC"=>"农业银行","PSBC"=>"邮储银行","CCB"=>"建设银行",
	   //     "CMB"=>"招商银行","BOC"=>"中国银行","COMM"=>"交通银行","SPDB"=>"浦发银行","GDB"=>"广发银行",
	   //     "CMBC"=>"民生银行","PAB"=>"平安银行","CEB"=>"光大银行","CIB"=>"兴业银行","CITIC"=>"中信银行"
	   //     ];
    // }
    
}
